package com.ma.service.impl;


import com.github.pagehelper.PageHelper;
import com.ma.entity.SysMenu;
import com.ma.entity.SysRole;
import com.ma.entity.SysUser;
import com.ma.mapper.SysUserMapper;
import com.ma.service.SysMenuService;
import com.ma.service.SysRoleMenuService;
import com.ma.service.SysRoleService;
import com.ma.service.SysUserService;
import com.ma.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Slf4j
@Service
public class SysUserServiceImpl  implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public SysUser getAllByUsername(String username) {
        return sysUserMapper.getAllByUsername(username);
    }
    @Override
    public SysUser getByUsernameById(Long id) {
        return sysUserMapper.getByUsernameById(id);
    }

    @Override
    public String getUserAuthorityInfo(Long id) {
        String authority = "";
            //hasKey 判断key是否存在
        if (redisUtil.hasKey("GrantedAuthority:"+sysUserMapper.getByUsernameById(id).getUsername())){
                                //普通缓存获取
            authority= (String) redisUtil.get("GrantedAuthority:"+sysUserMapper.getByUsernameById(id).getUsername());
        }else {

        //获取角色
       /* SELECT NAME   FROM    sys_role  WHERE
        id in ( SELECT role_id FROM sys_user_role WHERE user_id = '1' )*/
        List<SysRole> roles = sysRoleService.selectCodeById(id);
        if (roles.size() > 0) {
            String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
            authority = roleCodes.concat(",");
            log.info("用户ID - {} ---角色：{}", id, authority);
        }

        //获取菜单操作编码
   /*     SELECT DISTINCT   rm.menu_id FROM    sys_user_role ur   JOIN sys_role_menu rm
        ON     ur.role_id=rm.role_id     WHERE ur.user_id ='1';*/

        List<Long> selectMenuIdByIds=sysRoleMenuService.selectMenuIdById(id);
           if (selectMenuIdByIds.size()>0){
               List<SysMenu> sysMenuList=null;
               for (int i = 0; i <selectMenuIdByIds.size() ; i++) {
                   sysMenuList=sysMenuService.selectPermsById(selectMenuIdByIds.get(i));
                   String roleCodes = sysMenuList.stream().map(s ->  s.getPerms()).collect(Collectors.joining(","));
                   authority=authority+roleCodes+",";
               }
               log.info("用户ID - {} ---拥有的权限：{}", id, authority);
               }
        //使用redis做用户权限数据缓存 缓存时间为一天  set()普通缓存放入并设置时间
        redisUtil.set("GrantedAuthority:"+sysUserMapper.getByUsernameById(id).getUsername()
                            ,authority,60*60);
        }
        return authority;
    }

    //通过改变用户权限
    public void clearUserAuthorityInfo(String username) {
        //删除缓存
        redisUtil.del("GrantedAuthority:"+username);
    }

    //通过改变菜单
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
/*        SELECT su.* FROM    sys_user_role ur LEFT JOIN
        sys_role_menu rm   ON    rm.role_id=ur.role_id     LEFT JOIN
        sys_user su    ON   su.id=ur.user_id       WHERE menu_id=2*/
        List<SysUser> sysUsers=sysUserMapper.getALLByMenuId(menuId);
        for (SysUser sysUser : sysUsers) {
           this.clearUserAuthorityInfo(sysUser.getUsername());
        }
    }

    //通过改变用户角色
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        /*SELECT * FROM  sys_user  WHERE
        id IN ( SELECT user_id FROM sys_user_role WHERE role_id = 6 )*/
        List<SysUser> sysUsers=sysUserMapper.getAllByRoleId(roleId);
        for (SysUser sysUser : sysUsers) {
            this.clearUserAuthorityInfo(sysUser.getUsername());
        }
    }

    @Override
    public SysUser getUserById(Long id) {
        return sysUserMapper.getUserById(id);
    }

    @Override
    public List<SysUser> listByUsername(String username, Integer page, Integer rows) {
        //设置分页信息
        PageHelper.startPage(page,rows);
        List<SysUser> SysUser=sysUserMapper.listByUsername(username);
        return SysUser;
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void save(SysUser sysUser) {
        sysUserMapper.save(sysUser);
    }

    @Override
    public void deleteUserById(Long id) {
        sysUserMapper.deleteUserById(id);
    }

    @Override
    public void repassByUserId(SysUser sysUser) {
        sysUserMapper.repassByUserId(sysUser);
    }


}
